<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <!-- <el-form-item>
          <el-input v-model="filters.username" placeholder="用户名"></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-input style="width:200px;" v-model.trim="filters.clauseTitle" size="small" placeholder="条款标题"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input style="width:200px;" v-model.trim="filters.kindCode" size="small" placeholder="条款代码"></el-input>
        </el-form-item>
        <!--  -->
        <el-form-item style="float:right;">
          <el-button type="primary" v-show="exportBtnVisible" class="button_style" size="small" icon="upload2" @click="exportExcels">导出</el-button>
        </el-form-item>
        <!--  -->
        <el-form-item style="float:right;">
          <el-button type="primary" v-show="addBtnVisible" class="button_style" size="small" icon="plus" @click="handleAdd">新增</el-button>
        </el-form-item>
        <!--  -->
        <el-form-item style="float:right;">
          <el-button type="primary" v-show="queryBtnVisible" class="button_style" size="small" icon="search" v-on:click="getcustoms(true)">查询</el-button>
        </el-form-item>

      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="clauses" stripe border :height="winHeight-188" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <!-- <el-table-column type="selection" width="55">
      </el-table-column> -->
      <!-- <el-table-column prop="serialNo" label="序号" width="120" sortable>
      </el-table-column> -->

      <!-- <el-table-column prop="userid" label="序号" align="center" width="100px" sortable>
          <template scope="scope">
            <span style="color:#20a0ff;cursor:pointer;text-decoration:underline;">{{scope.row.serialNumber}}</span>
          </template>
      </el-table-column> -->
      <el-table-column prop="serialNumber" align="center" label="序号" width="100">
      </el-table-column>
      <el-table-column prop="clauseTitle" align="center" label="条款标题" min-width="130" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="kindCode" align="center" label="条款代码" min-width="80">
      </el-table-column>
      <el-table-column prop="planId" align="center" label="计划ID" min-width="120" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="createTime" align="center" label="创建时间" min-width="130" sortable>
      </el-table-column>
      <el-table-column prop="updateTime" align="center" label="更新时间" min-width="130" sortable>
      </el-table-column>
      <!-- <el-table-column prop="status" label="状态" min-width="120" :formatter="formatStatus" sortable>
      </el-table-column> -->
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <!--  -->
          <el-button v-show="updateBtnVisible" size="small" type="warning" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <!-- <el-button type="primary" size="small" v-show="buttonShows(scope.$index, scope.row)"  @click="handleRecover(scope.$index, scope.row)">恢复</el-button> -->
          <!--  -->
          <el-button type="danger" v-show="deleteBtnVisible" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!-- <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button> -->

      <el-pagination style="float:right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page" :page-sizes="[10, 20, 40, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
      <el-form label-width="120px" :model="addForm" :rules="addFormRules" ref="addForm">
        <el-row>
          <el-col :xs="24" :sm="20" :md="13" :lg="10">
            <el-form-item label="条款序号:" prop="serialNumber">
              <el-input v-model="addForm.serialNumber" auto-complete="off">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="20" :md="16" :lg="14">
            <el-form-item label="条款代码:" prop="kindCode">
              <el-input v-model="addForm.kindCode" auto-complete="off">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="20" :md="20" :lg="20">
            <el-form-item label="条款标题:" prop="clauseTitle">
              <!--  <el-input v-model="addForm.clauseTitle" auto-complete="off" >
                      </el-input> -->
              <el-autocomplete v-model="addForm.clauseTitle" style="width:100%;" :fetch-suggestions="querySearchAsync" placeholder="请输入标题名" @select="handleSelect">
              </el-autocomplete>

            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xs="24" :sm="20" :md="20" :lg="20">
            <el-form-item label="计划ID:" prop="name">
              <el-tooltip class="item" effect="dark" :content="addForm.planId" placement="top">
                <el-input v-model="addForm.planId" auto-complete="off">
                </el-input>
              </el-tooltip>
              <span style="color:#ff4949;">多个计划ID用,隔开</span>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
                  <el-col :xs="24" :sm="20" :md="16" :lg="11">
              <el-form-item label="添加人" prop="username">
                  <el-input v-model="addForm.username" :readonly='true' auto-complete="off"></el-input>
              </el-form-item>
              </el-col>
                <el-col :xs="24" :sm="20" :md="16" :lg="11">
              <el-form-item label="添加时间">
                  <el-input v-model="addForm.branchcode"  auto-complete="off"></el-input>
              </el-form-item>
              </el-col>
              </el-row> -->
        <el-form-item label="条款内容:">
          <div class="kboder" @click="Preview('add')" style="height:120px;min-width:160px;width:80%;">
            <div id="addPreview" class="ksboder">
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog title="修改" v-model="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
        <el-row>
          <el-col :xs="24" :sm="13" :md="13" :lg="10">
            <el-form-item label="条款序号:" prop="serialNumber">
              <el-input v-model="editForm.serialNumber" auto-complete="off">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="20" :md="16" :lg="14">
            <el-form-item label="条款代码:" prop="kindCode">
              <el-input v-model="editForm.kindCode" auto-complete="off">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="20" :md="20" :lg="20">
            <el-form-item label="条款标题:" prop="clauseTitle">
              <!-- <el-input v-model="editForm.clauseTitle" auto-complete="off" >
                      </el-input> -->
              <el-autocomplete v-model="editForm.clauseTitle" style="width:100%;" :fetch-suggestions="querySearchAsync" placeholder="请输入标题名" @select="handleSelect">
              </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="20" :md="20" :lg="20">
            <el-form-item label="计划ID:" prop="name">
              <el-tooltip class="item" effect="dark" :content="editForm.planId" placement="top">
                <el-input v-model="editForm.planId" auto-complete="off">
                </el-input>
              </el-tooltip>
              <span style="color:#ff4949;">多个计划ID用,隔开</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="条款内容:">
          <div class="kboder" @click="Preview('edit')" style="height:120px;min-width:160px;width:80%;">
            <div id="editPreview" class="ksboder">
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改" size="large" v-model="editorVisible" :close-on-click-modal="false">
      <!-- <editor ref="myTextEditor" :fileName="'myFile'" :canCrop="canCrop" :uploadUrl="uploadUrl" v-model="content">
      </editor> -->
      <vue-editor v-model="content"></vue-editor>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editorVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editorSubmit" :loading="editorLoading">确定</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'

import commons from '../../common/js/common'
//import NProgress from 'nprogress'
import { mapState, mapActions } from 'vuex'
import { clauseList, addClause, removeClause, base, clauseTitleList } from '../../api/api';
import editor from '../../components/Quilleditor.vue';
import { VueEditor, Quill } from 'vue2-editor';
export default {
  components: {
    VueEditor,
    Quill,
    editor
  },
  data() {
    return {
      restaurants: [],
      state4: '',
      timeout: null,
      canCrop: false,
      uploadUrl: base + '/cxb/admin/uploadWeb/upload',
      roles: [],
      content: '',
      filters: {
        kindCode:'',
        clauseTitle: ''
      },
      commonObj: '',
      exportTotal: 0,
      loading: '',
      clauses: [],
      lists: [],
      total: 0,
      page: 1,
      pageSize: 10,
      listLoading: false,
      editorLoading: false,
      sels: [],//列表选中列
      defaultData: [],
      userid: '',
      addFormVisible: false,//新增界面是否显示
      editFormVisible: false,//修改界面是否显示
      editorVisible: false,//
      editLoading: false,
      addFormRules: {
        kindCode: [
          { required: true, message: '请输入条款代码', trigger: 'blur' }
        ],
        serialNumber:[
          { required: true, message: '请输入条款序号', trigger: 'blur' }
        ],
        clauseTitle: [
          { required: true, message: '请输入条款标题', trigger: 'blur' }
        ]
      },
      editFormRules: {
        kindCode: [
          { required: true, message: '请输入条款代码', trigger: 'blur' }
        ],
        clauseTitle: [
          { required: true, message: '请输入条款标题', trigger: 'blur' }
        ]
      },
      //修改界面数据
      editForm: {
        id: '',
        planId: '',
        kindCode: '',
        serialNumber: '',
        clauseTitle: '',
        clauseContent: ''
      },
      detailFormVisible: false,//新增界面是否显示
      addLoading: false,
      IsShow: false,
      detailFormRules: {
        // name: [
        //   { required: true, message: '请输入姓名', trigger: 'blur' }
        // ]
      },
      //新增界面数据
      addForm: {
        id: '',
        planId: '',
        kindCode: '',
        serialNumber: '',
        clauseTitle: '',
        clauseContent: ''
      },

      queryBtnVisible: false,
      addBtnVisible: false,
      exportBtnVisible: false,
      updateBtnVisible: false,
      deleteBtnVisible: false
    }
  },
  computed: mapState([
    'winWidth',
    'winHeight'
  ]),
  methods: {
    formatCreate: function (row, column) {
      return commons.getDaytime(row.createTime, 1, false);
    },
    formatUpdate: function (row, column) {
      return commons.getDaytime(row.updateTime, 1, false);
    },
    initial() {

      clauseTitleList().then((res) => {
        if (res.data.success) {
          for (var i in res.data.result) {
            this.restaurants.push({
              value: res.data.result[i]
            });
          }
        }
      }).catch(() => {

      });
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 1000);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.indexOf(queryString.toLowerCase()) != -1);
      };
    },
    handleSelect() {

    },
    handleCurrentChange(val) {
      this.page = val;
      this.getcustoms(true);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getcustoms(true);
    },
    //获取用户列表
    getcustoms(bool) {
      let para = new FormData();
      para.append("pageSize", bool ? this.pageSize : this.exportTotal);
      para.append("pageNumber", bool ? this.page : 1);
      para.append("clauseTitle", this.filters.clauseTitle);
      para.append("kindCode", this.filters.kindCode);
      this.listLoading = bool;
      //NProgress.start();
      if (!bool) {
        this.loading = this.$loading({
          lock: true,
          text: '正在导出',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      }
      clauseList(para).then((res) => {
        this.lists = res.data.result.content;
        this.total = res.data.result.totalElements;
        this.exportTotal = res.data.result.totalElements;
        this.listLoading = false;
        if (!bool) {
          this.loading.close();
          this.export2Excel();
        }
        else {
          this.clauses = res.data.result.content;
          this.defaultData = res.data.result.content;
        }
      });
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let para = new FormData();
        para.append("id", row.id);
        removeClause(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getcustoms(true);
        });
      }).catch(() => {

      });
    },

    //table导出excel
    exportExcels: function () {
      this.getcustoms(false);
    },
    export2Excel: function () {
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../vendor/Export2Excel');
        const tHeader = ['序号', '条款标题', '条款代码', '计划ID', '创建时间', '更新时间'];
        const filterVal = ['serialNumber', 'clauseTitle', 'kindCode', 'planId', 'createTime', 'updateTime'];
        const list = this.lists;
        // for (var i in list) {
        //   list[i].createTime = commons.getDaytime(list[i].createTime, 1, false);
        //   list[i].updateTime = commons.getDaytime(list[i].updateTime, 1, false);
        // }
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '条款列表excel');
      })
    },
    formatJson: function (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    //显示修改界面
    handleEdit: function (index, row) {
      this.editFormVisible = true;
      this.editForm = this.defaultData[index];
      setTimeout(function () {
        $('#editPreview').html(row.clauseContent);
      }, 100);

    },
    //显示新增界面
    handleAdd: function () {
      this.addFormVisible = true;
      this.state4 = '';
      this.addForm = {
        id: '',
        planId: '',
        kindCode: '',
        serialNumber: '',
        clauseTitle: '',
        clauseContent: ''
      };
      $('#addPreview').html('');
    },
    //新增提交
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            // let para = Object.assign({}, this.addForm);
            let para = this.addForm;
            addClause(para).then((res) => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['addForm'].resetFields();
                this.addFormVisible = false;
                this.getcustoms(true);
              }
              else {
                this.$message({
                  message: res.data.result,
                  type: 'error'
                });
              }
              this.addLoading = false;
              //NProgress.done();

            }).catch(() => {
              this.addLoading = false;
            });
          });
        }
      });
    },
    //修改
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            // let para = Object.assign({}, this.editForm);
            let para = this.editForm;
            para.startDate = (!para.startDate || para.startDate == '') ? '' : util.formatDate.format(new Date(para.startDate), 'yyyy-MM-dd');
            para.endDate = (!para.endDate || para.endDate == '') ? '' : util.formatDate.format(new Date(para.endDate), 'yyyy-MM-dd');
            addClause(para).then((res) => {
              this.editLoading = false;
              //NProgress.done();
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
                this.editFormVisible = false;
                this.getcustoms(true);
              }
              else {
                this.$message({
                  message: res.data.result,
                  type: 'error'
                });
                this.$refs['editForm'].resetFields();
                this.editFormVisible = false;
                this.getcustoms(true);
              }

            }).catch(() => {
              this.editLoading = false;
            });;
          });
        }
      });
    },
    Preview(str) {
      let _this = this;
      _this.editorVisible = true;
      _this.content = '';
      if (str == "add") {
        _this.content = $('#addPreview').html();
        _this.commonObj = 'addPreview';
      }
      else {
        _this.content = $('#editPreview').html();
        _this.commonObj = 'editPreview';
      }
      this.$store.commit('EDITORPICTURE_VALUE', 'clause');
    },
    editorSubmit: function () {
      let _this = this;
      $('#' + _this.commonID).html(_this.content);
      if (_this.commonObj == "addPreview") {
        // _this.content
        $('#addPreview').html(_this.content);
        _this.addForm.clauseContent = _this.content;
      }
      else {
        $('#editPreview').html(_this.content);
        _this.editForm.clauseContent = _this.content;
      }
      _this.editorVisible = false;
    },

    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id).toString();
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        // let para = { ids: ids };
        let para = new FormData();
        para.append("ids", ids);
        removeAd(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getcustoms(true);
        });
      }).catch(() => {

      });
    },

    btnShow: function () {
      let thisData = JSON.parse(sessionStorage.getItem('145'));
      let _this = this;
      $.each(thisData, function (i, j) {
        if (thisData[i] == "clauseQuery") {
          _this.queryBtnVisible = true;
        }
        if (thisData[i] == "clauseAdd") {
          _this.addBtnVisible = true;
        }
        if (thisData[i] == "clauseExport") {
          _this.exportBtnVisible = true;
        }
        if (thisData[i] == "clauseUpdate") {
          _this.updateBtnVisible = true;
        }
        if (thisData[i] == "clauseRemove") {
          _this.deleteBtnVisible = true;
        }
      });
    }
  },
  mounted() {
    this.getcustoms(true);
    this.initial();
    this.btnShow();
  }
}

</script>

<style scoped>
.kboder {
  border: 1px solid #bfcbd9;
  overflow-y: scroll;
  overflow-x: hidden;
  cursor: pointer;
}
.ksboder {
  margin: 10px;
  word-wrap: break-word;
}
/*.toolbar {
  padding:10px;
}*/
/*.toolbar .el-form-item{
  margin-bottom: 0px !important;
  margin-left: 10px;
}*/
</style>